package com.jt.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jt.mapper.FileMapper;
import com.jt.vo.ImageVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    String dirPath = "E:/cgb2108/images";
    @Override
    public ImageVO upload(MultipartFile file) {
        String filename = file.getOriginalFilename();
        filename = filename.toLowerCase();
        if (!filename.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            if (height == 0 || width == 0){
                return null;
            }

            String datedir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String dateDirPath = dirPath + datedir;
            File dirFile = new File(dateDirPath);
            if (!dirFile.exists()){
                dirFile.mkdirs();
            }

            final String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileType = filename.substring(filename.lastIndexOf("."));
            String newFileName = uuid + fileType;

            String path = dateDirPath + newFileName;
            file.transferTo(new File(path));

            String virtualPath = datedir + newFileName;
            String url = "https://img14.360buyimg.com/n1/s546x546_jfs/t1/222493/36/2768/130956/61921070Ee4e511a5/762496ebd05718f9.jpg";
            return new ImageVO(virtualPath,url,newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void deleteFile(String virtualPath) {
        String filePath = dirPath + virtualPath;
        File file = new File(filePath);
        if (file.exists())
            file.delete();
    }
}
